package com.cooper.controllers;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import net.paoding.rose.web.ErrorHandlerAdapter;
import net.paoding.rose.web.Invocation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cooper.core.JsonResult;

/**
 * 
* @Description: 
* @version: v1.0.0
* @author: tianlg
* @date: Jan 8, 2015 10:38:21 AM
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* Jan 8, 2015      tianlg          v1.0.0
 */
public class ErrorHandler extends ErrorHandlerAdapter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public Object onError(Invocation inv, Throwable ex) throws Throwable {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		PrintStream printStream = new PrintStream(bos);
		ex.printStackTrace(printStream);
		String strTrace = new String(bos.toByteArray());
		
		Class<?> returnType = inv.getMethod().getReturnType();
		logger.error("Error:{}", ex);
		if(String.class == returnType){
			inv.addModel("actionPath", inv.getRequestPath().getUri());
			inv.addModel("error", ex.getMessage());
			inv.addModel("trace", strTrace);
			return "Error";
		} else {
			JsonResult json = new JsonResult();
			json.setMessage("Error:{0}", ex.getMessage());
			return json;
		}
	}

}
